package com.lanou3g.k12.service.impl;

import com.lanou3g.k12.entity.*;
import com.lanou3g.k12.mapper.*;
import com.lanou3g.k12.service.CouponChapterService;
import com.lanou3g.k12.service.CouponCodeService;
import com.lanou3g.k12.service.CouponService;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class CouponServiceImpl implements CouponService {

    @Autowired
    private CouponMapper couponMapper;

    @Autowired
    private CouponCodeService couponCodeService;

    @Autowired
    private CarouselMapper carouselMapper;

    @Autowired
    CourseMapper courseMapper;

    @Autowired
    private CouponChapterService couponChapterService;

    @Autowired
    private CouponCodeMapper couponCodeMapper;

    @Autowired
    private ChapterMapper chapterMapper;

    //查询所有
    @Override
    public List<Coupon> findAllCoupon() {
        List<Coupon> allCoupon = couponMapper.findAllCoupon();
        List<Coupon> allCoupons = couponMapper.selectCoupon();
        //循环兑换券表，判断是否兑换券失效
        for (Coupon coupon : allCoupons) {
            if (coupon.getEndTime() == null) {
                continue;
            }
            long endTime = coupon.getEndTime().getTime();
            Long id = coupon.getId();
            if (endTime <= new Date().getTime()) {
                couponMapper.updateStatus(id);
                couponCodeMapper.updateByCpId(id);
            }
        }
        return allCoupons;
    }

    //模糊查询
    @Override
    public List<Coupon> search(String keyword) {
        List<Coupon> byKeyword = couponMapper.findByKeyword("%" + keyword + "%");
        return byKeyword;
    }

    //新增兑换券

    /**
     * @param coupon 对象接收
     * @param ids    传过来的章节id数组
     * @return
     */
    @Override
    public int couponInsert(Coupon coupon, Long[] ids, Date beginTime, Date endTime) {
        coupon.setBeginTime(beginTime);
        coupon.setEndTime(endTime);
        Date date = new Date();
        coupon.setCreateTime(date);
        coupon.setUpdateTime(date);
        //把前端传过来的数组根据课程分类排序,以方便下一步循环比较
        List<Long> longs = chapterMapper.searchByIds(ids);
        //课程名初始化
        String course = "";
        //字符串初始化
        String str = "";
        //变量1,可能有一点点用
        int j = 1;
        //循环新集合,其目的是拼接字符串
        for (int i = 0; i < longs.size(); i++) {
            //获取章节名,cid
            Chapter chapter = chapterMapper.findById(longs.get(i));
            Long cid = chapter.getCid();
            //通过cid找到课程
            Course course1 = courseMapper.searchByID(cid);
            //如果第一个直接把课程名赋给course
            if (i == 0) {
                course = course1.getName();
            }
            //与下一个课程名字作比较,如果相同执行
            if (course.equals(course1.getName())) {
                //第一个直接拼接"课程名"+"("
                if (j == 1) {
                    str = str + course + "(";
                }
                //循环拼接
                str = str + chapter.getName() + ",";
                //变量赋值
                course = course1.getName();
                j++;
            } else {
                //当课程比较发现不为同一个课程时,截取字符串str,去掉",",拼接")"
                str = str.substring(0, str.length() - 1);
                str = str + ")" + " ";
                course = course1.getName();
                //再拼接"课程名"+":"+"("和章节名
                str = str + course + "(" + chapter.getName() + ",";
            }
            //如果发现循环结束,i为最后一个,截取字符串str,去掉",",拼接")"
            if (i == longs.size() - 1) {
                str = str.substring(0, str.length() - 1);
                str = str + ")";
                break;
            }
        }
        //放到coupon对象里
        coupon.setCourseName(str);
        //执行插入方法
        int insert = couponMapper.couponInsert(coupon);
        //在插入的时候获取coupon库存数量
        Integer stock = coupon.getStock();
        //去兑换券码的表中查询为空的数量
        List<CouponCode> couponCodes = couponCodeService.searchCode();
        //判断,如果库存中的未使用兑换券码(cpId为null)小于于需求或不存在为空的兑换券码
        if (couponCodes.size() < stock || couponCodes.size() == 0) {
            if (couponCodes.size() != 0) {
                List<CouponCode> couponCodes1 = couponCodes.subList(0, couponCodes.size());
                List<Long> array = new ArrayList<>();
                for (CouponCode couponCode : couponCodes1) {
                    Long id = couponCode.getId();
                    array.add(id);
                }
                couponCodeService.update(coupon.getId(), array);
                //此时需要的stock为减去已经更改过得
                stock = stock - couponCodes1.size();
                Integer status = coupon.getStatus();
                Long cpId = coupon.getId();
                couponCodeService.add(stock, status, cpId);
            } else {
                //查询为null的码返回长度等于0时直接批量添加
                Integer status = coupon.getStatus();
                Long cpId = coupon.getId();
                couponCodeService.add(stock, status, cpId);
            }
        } else {
            //库存中为null的码大于需求时,直接更改
            List<CouponCode> couponCodes1 = couponCodes.subList(0, stock);
            List<Long> array = new ArrayList<>();
            for (CouponCode couponCode : couponCodes1) {
                Long id = couponCode.getId();
                array.add(id);
            }
            couponCodeService.update(coupon.getId(), array);
        }
        //插入中间表
        Long cpId1 = coupon.getId();
        couponChapterService.insert(cpId1, ids);
        return insert;
    }

    //通过ID查询
    @Override
    public Coupon findCouponById(Long id) {
        Coupon couponId = couponMapper.findCouponById(id);
        return couponId;
    }

    //查询所有的兑换码，生成excel表格

    /**
     * 通过传值  查询 调用生成表格方法
     *
     * @param id 兑换码id
     * @return
     */
    @Override
    public InputStream getAllCodes(Long id) {
        List<CouponCode> allCodes = couponMapper.getAllCodes(id);

        HSSFWorkbook sheets = new HSSFWorkbook();//创建一个新工作浦
        Sheet sheet = sheets.createSheet("码页");

        CreationHelper creationHelper = sheets.getCreationHelper();

        //创建单元格样式  负责表格时间格式
        CellStyle cellStyle = sheets.createCellStyle();
        cellStyle.setDataFormat(creationHelper.createDataFormat().getFormat("yyyy-MM-dd hh:mm:ss")); //设置时间样式

        //负责表格对齐方式
        CellStyle cellStyle1 = sheets.createCellStyle();
        cellStyle1.setAlignment(HorizontalAlignment.LEFT);//设置单元格水平方向对齐方式  居中
        cellStyle1.setVerticalAlignment(VerticalAlignment.CENTER);//设置单元格垂直方向对齐方式  居中

        //设置字体样式风格
        HSSFCellStyle cellStyle2 = sheets.createCellStyle();
        HSSFFont font = sheets.createFont();  //设置字体样式
        font.setFontName("微软雅黑");
        font.setFontHeightInPoints((short) 16);//设置字号
        font.setColor(HSSFColor.HSSFColorPredefined.RED.getIndex());//设置字体颜色
        cellStyle2.setFont(font);  //字体风格放入  风格

        //设置表头字体样式
        HSSFCellStyle cellStyle4 = sheets.createCellStyle();
        HSSFFont font1 = sheets.createFont();  //设置字体样式
        font1.setFontName("微软雅黑");
        font1.setFontHeightInPoints((short) 12);//设置字号
        font1.setColor(HSSFColor.HSSFColorPredefined.BLUE.getIndex());//设置字体颜色
        cellStyle4.setFont(font1);  //字体风格放入  风格


        Row row1 = sheet.createRow(0);
        sheet.setColumnWidth(0, 20 * 256);
        sheet.setColumnWidth(1, 30 * 256);
        sheet.setColumnWidth(2, 25 * 256);
        sheet.setColumnWidth(3, 25 * 256);
        sheet.setColumnWidth(4, 20 * 256);
        sheet.setColumnWidth(5, 20 * 256);
        sheet.setColumnWidth(6, 15 * 256);
        row1.setHeightInPoints(30);//设置行的高度是50
        row1.createCell(0).setCellValue("兑换券名字");
        row1.createCell(1).setCellValue("兑换课程");
        row1.createCell(2).setCellValue("开始日期");
        row1.createCell(3).setCellValue("截止日期");
        row1.createCell(4).setCellValue("目标用户");
        row1.createCell(5).setCellValue("兑换码");
        row1.createCell(6).setCellValue("兑换码状态");
        row1.setRowStyle(cellStyle1);
        row1.setRowStyle(cellStyle4);


        int i = 1;
        for (CouponCode couponCode : allCodes) {
            Row row = sheet.createRow(i);
            sheet.setColumnWidth(0, 20 * 256);
            sheet.setColumnWidth(1, 30 * 256);
            sheet.setColumnWidth(2, 25 * 256);
            sheet.setColumnWidth(3, 25 * 256);
            sheet.setColumnWidth(4, 20 * 256);
            sheet.setColumnWidth(5, 20 * 256);
            sheet.setColumnWidth(6, 15 * 256);
            row.setHeightInPoints(30);//设置行的高度是50

            //获取兑换券课程信息
            Coupon coupon = carouselMapper.couponById(couponCode.getCpId());
            String ing = "没有课程";
            String courseName = coupon.getCourseName();
            if (!(courseName == null)) {
                ing = courseName;
            }

            //兑换券名字
            Cell cell3 = row.createCell(0);
            cell3.setCellValue(coupon.getName());
            cell3.setCellStyle(cellStyle1);
            cell3.setCellStyle(cellStyle2);

            Cell cell = row.createCell(1);
            cell.setCellValue(ing);// 给单元格设置值
            cell.setCellStyle(cellStyle1);
            cell.setCellStyle(cellStyle2);

            //开始日期
            Cell cell4 = row.createCell(2);
            cell4.setCellValue(coupon.getBeginTime());
            cell4.setCellStyle(cellStyle1);
            cell4.setCellStyle(cellStyle2);
            cell4.setCellStyle(cellStyle);

            //截止日期
            Cell cell5 = row.createCell(3);
            cell5.setCellValue(coupon.getEndTime());
            cell5.setCellStyle(cellStyle1);
            cell5.setCellStyle(cellStyle2);
            cell4.setCellStyle(cellStyle);

            //目标用户
            Cell cell6 = row.createCell(4);
            cell6.setCellValue(coupon.getTarget());
            cell6.setCellStyle(cellStyle1);
            cell6.setCellStyle(cellStyle2);


            //兑换券码
            Cell cell7 = row.createCell(5);
            cell7.setCellValue(couponCode.getCode());
            cell7.setCellStyle(cellStyle1);
            cell7.setCellStyle(cellStyle2);

            //使用状态
            Cell cell8 = row.createCell(6);
            String str = null;
            if (couponCode.getStatus() == 0) {
                str = "未使用";
            } else {
                str = "已使用";
            }
            cell8.setCellValue(str); //更改0.1状态
            cell8.setCellStyle(cellStyle1);
            cell8.setCellStyle(cellStyle2);


            i++;
        }
        //FileOutputStream stream = new FileOutputStream("D:\\用户信息表1.xls");//创建表格存放路径
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        //sheets.write(stream);
        try {
            sheets.write(bo);
        } catch (IOException e) {
            e.printStackTrace();
        }
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bo.toByteArray());


        return inputStream;
    }


    /**
     * 兑换码 兑换功能
     *
     * @param code 需要验证的兑换码
     * @return
     */
    @Override
    public Boolean voucherCode(String code, String phone) {
        CouponCode couponCode = couponMapper.voucherByCode(code);
        Long uid = couponMapper.phoneByUserId(phone);
        if (couponCode.getStatus() == 0) {
            //通过兑换卷id 查询中间表 查出 兑换券可兑换的课程
            List<Long> chId = couponMapper.chIdByCpid(couponCode.getCpId());
            for (Long aLong : chId) {
                couponMapper.addUserChapter(uid, aLong);
            }

            couponMapper.upStatus(couponCode.getId());
            //更改兑换券状态之后  在用户和兑换券表中建立状态
            Date date = new Date();
            UserCoupon userCoupon = new UserCoupon();
            userCoupon.setuId(uid);
            userCoupon.setcId(couponCode.getCpId());
            userCoupon.setUseTime(date);
            couponMapper.userAndCoupon(userCoupon);
            return true;
        } else {
            return false;
        }
    }


    /**
     * 查询对应用户
     *
     * @return 返回兑换券兑换记录信息
     */
    //查询兑换记录
    @Override
    public List<CouponRecord> couponRecord(String phone) {
        List<CouponRecord> listRecord = new ArrayList<>();
        Long uid = couponMapper.phoneByUserId(phone);
        //用户对应的兑换所有兑换卷
        List<UserCoupon> list = couponMapper.recordByUid(uid);
        if (list.size() > 100) {
            //当查询结果数量 大于100时  默认只取100条
            list = list.subList(0, 100);
        } else {
            for (UserCoupon userCoupon : list) {
                //获取兑换券名字
                Coupon coupon = couponMapper.couponNameById(userCoupon.getcId());
                CouponRecord couponRecord = new CouponRecord();
                couponRecord.setName(coupon.getName());
                couponRecord.setUseTime(userCoupon.getUseTime());
                couponRecord.setDetails(coupon.getCourseName());
                listRecord.add(couponRecord);
            }
        }
        return listRecord;
    }

}
